package com.zrwl.poscloud.core.restapi.admin.baseInfo;
import com.zrwl.poscloud.base.entity.*;
import com.zrwl.poscloud.commons.utils.*;
import com.zrwl.poscloud.core.annotion.AuthorityVerify.AuthorityVerify;
import com.zrwl.poscloud.core.annotion.OperationLogger.OperationLogger;
import com.zrwl.poscloud.commons.exception.ThrowableUtils;
import com.zrwl.poscloud.commons.validator.group.Delete;
import com.zrwl.poscloud.commons.validator.group.GetList;
import com.zrwl.poscloud.commons.validator.group.Insert;
import com.zrwl.poscloud.commons.validator.group.Update;
import com.zrwl.poscloud.xo.service.*;
import com.zrwl.poscloud.xo.vo.StudentScoreSubjectDetailVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.zrwl.poscloud.xo.vo.StudentScoreTotalDetailVO;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * 总分明细 controller api类
 *
 * @author 刘思童 AutoGenerate
 * @date 2023-03-10
 */
@RestController
@Api(value = "总分明细相关接口", tags = {"总分明细相关接口"})
@RequestMapping("/studentScoreTotalDetail")
@Slf4j
public class StudentScoreTotalDetailRestApi {
    @Autowired
    private StudentScoreBathService studentScoreBathService;
    @Autowired
    private StudentScoreTotalDetailService studentScoreTotalDetailService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private DeptService deptService;
    @AuthorityVerify
    @ApiOperation(value = "获取总分明细列表", notes = "获取总分明细列表", response = String.class)
    @PostMapping("/getList")
    public String getList(@Validated({GetList.class}) @RequestBody StudentScoreTotalDetailVO studentScoreTotalDetailVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("获取总分明细列表: {}", studentScoreTotalDetailVO);
        return ResultUtil.successWithData(studentScoreTotalDetailService.getPageList(studentScoreTotalDetailVO));
    }
    @AuthorityVerify
    @OperationLogger(value = "重新生成排名")
    @ApiOperation(value = "重新生成排名", notes = "重新生成排名", response = String.class)
    @PostMapping("/generateRank")
    public String generateRank(@Validated({Insert.class}) @RequestBody StudentScoreTotalDetailVO studentScoreTotalDetailVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("重新生成排名: {}", studentScoreTotalDetailVO);
        return studentScoreTotalDetailService.generateRank(studentScoreTotalDetailVO);
    }
    @AuthorityVerify
    @OperationLogger(value = "根据明细生成总分")
    @ApiOperation(value = "根据明细生成总分", notes = "根据明细生成总分", response = String.class)
    @PostMapping("/generateRankTotalScore")
    public String generateRankTotalScore(@Validated({Insert.class}) @RequestBody StudentScoreTotalDetailVO studentScoreTotalDetailVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("根据明细生成总分: {}", studentScoreTotalDetailVO);
        return studentScoreTotalDetailService.generateRankTotalScore(studentScoreTotalDetailVO);
    }
    @AuthorityVerify
    @ApiOperation(value = "获取总分明细列表", notes = "获取总分明细列表", response = String.class)
    @PostMapping("/getAllList")
    public String getAllList(@Validated({GetList.class}) @RequestBody StudentScoreTotalDetailVO studentScoreTotalDetailVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("获取总分明细列表: {}", studentScoreTotalDetailVO);
        return ResultUtil.successWithData(studentScoreTotalDetailService.getAllList(studentScoreTotalDetailVO));
    }

    @AuthorityVerify
    @OperationLogger(value = "新增总分明细")    @ApiOperation(value = "新增总分明细", notes = "新增总分明细", response = String.class)
    @PostMapping("/add")
    public String add(@Validated({Insert.class}) @RequestBody StudentScoreTotalDetailVO studentScoreTotalDetailVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("新增总分明细: {}", studentScoreTotalDetailVO);
        StudentScoreBath studentScoreBath = studentScoreBathService.getById(studentScoreTotalDetailVO.getBatchUid());//获取当前批次
        Employee employee = employeeService.getByCode(studentScoreTotalDetailVO.getStudentCode());
        String companyName = deptService.getCompanyNameByCompanyCode(DeptUtil.getCompanyFull(DeptUtil.getCompanyShortCode(employee.getCompanyCode(), String.valueOf(Integer.parseInt(DeptUtil.getCompanyLevel(employee.getCompanyCode()))-1))));
        studentScoreTotalDetailVO.setSuperDeptName(companyName);
        return ResultUtil.successWithDataAndMessage(studentScoreTotalDetailService.singleImport(studentScoreTotalDetailVO,studentScoreBath),"添加成功");
    }

    @AuthorityVerify
    @OperationLogger(value = "修改总分明细")    @ApiOperation(value = "修改总分明细", notes = "修改总分明细", response = String.class)
    @PostMapping("/edit")
    public String edit(@Validated({Update.class}) @RequestBody StudentScoreTotalDetailVO studentScoreTotalDetailVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("修改总分明细: {}", studentScoreTotalDetailVO);
        return studentScoreTotalDetailService.edit(studentScoreTotalDetailVO);
    }
    @AuthorityVerify
    @OperationLogger(value = "上传Excel")
    @ApiOperation(value = "上传Excel", notes = "上传Excel", response = String.class)
    @PostMapping("/uploadExcel")
    public String uploadExcel(@RequestParam("file") List<MultipartFile> file, @RequestParam("batchUid") String batchUid, @RequestParam("maxErrorData") int maxErrorData) {
        //1获取当前批次
        StudentScoreBath studentScoreBath = studentScoreBathService.getById(batchUid);//获取当前批次
        //2Excel解析并判重
        List<Map<String, String>> list = new ArrayList<>();
        for (int i = 0; i < file.size(); i++) {
            MultipartFile fileO = file.get(i);
            if (fileO.isEmpty()) {
                continue;
            }
            list.addAll(ExcelUtil.ArrayList(file.get(i)));
        }
        Map<String, String> columnConfigMap = new HashMap<>();
        columnConfigMap.put("superDeptName", "上级机构");
        columnConfigMap.put("deptName", "班级");
        columnConfigMap.put("studentName", "姓名(后缀)");
        columnConfigMap.put("studentCode", "学号");
        List<StudentScoreTotalDetailVO> detailList = new LinkedList<>();//返回的错误数据
        /**
         * 遍历数据并进行校验
         */
        for (int i = 0; i < list.size(); i++) {
            StudentScoreTotalDetailVO studentScoreTotalDetailVO = new StudentScoreTotalDetailVO();//创建明细
            studentScoreTotalDetailVO.setBatchUid(studentScoreBath.getUid());
            if (list.get(i).size() == 0) {
                continue;
            }
            Map<String, String> row = list.get(i);
            //赋值给明细表
            for (Map.Entry<String, String> entry : columnConfigMap.entrySet()) {
                String name = entry.getValue();
                //赋值给明细表
                if (StringUtils.isNotEmpty(row.get(name)) && StringUtils.isNotEmpty(row.get(name).trim())) {
                    ClassUtil.setFieldValueByFieldName(entry.getKey(), studentScoreTotalDetailVO, row.get(name));
                }
            }
            if (StringUtils.isNotEmpty(row.get("分数")) && StringUtils.isNotEmpty(row.get("分数").trim())) {
                studentScoreTotalDetailVO.setTotalScore(Integer.parseInt(row.get("分数")));
            }
            if (StringUtils.isNotEmpty(row.get("总分")) && StringUtils.isNotEmpty(row.get("总分").trim())) {
                studentScoreTotalDetailVO.setTotalFull(Integer.parseInt(row.get("总分")));
            }
            try {
                studentScoreTotalDetailService.singleImport(studentScoreTotalDetailVO,studentScoreBath);
            }catch (RuntimeException e){
                studentScoreTotalDetailVO.setSummary(e.getMessage());
                detailList.add(studentScoreTotalDetailVO);
            }
            if (detailList.size() >= maxErrorData) {
                break;
            }
        }
        return ResultUtil.successWithDataAndMessage(detailList, "成功导入" + (maxErrorData > list.size() ? (list.size() - detailList.size()) : (detailList.size() == 0 ? list.size() : (maxErrorData - detailList.size()))) + "条数据，失败" + detailList.size() + "条数据！");
    }
    @AuthorityVerify
    @OperationLogger(value = "删除总分明细")    @ApiOperation(value = "删除总分明细", notes = "删除总分明细", response = String.class)
    @PostMapping("/delete")
    public String delete(@Validated({Delete.class}) @RequestBody StudentScoreTotalDetailVO studentScoreTotalDetailVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("删除总分明细: {}", studentScoreTotalDetailVO);
        return studentScoreTotalDetailService.delete(studentScoreTotalDetailVO);
    }

}
